package com.ls.rbac.utils;

/**
 * created by liush on 2025/6/28
 **/

// 这里使用hutool生成jwt工具类

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/** token：包括三个部分 header（）.payload.signature
 * */
@Component
public class JwtUtils {

    public static final String JWT_SECRET="telecom_rbac";

    public static final long EXPIRE_TIME = 30*60;

    public static String createToken(Map<String, Object> payload){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.plusSeconds(EXPIRE_TIME);// 过期时间
        payload.put(JWTPayload.ISSUED_AT, now);// 签发时间
        payload.put(JWTPayload.EXPIRES_AT, expireTime);// 过期时间
        payload.put(JWTPayload.NOT_BEFORE, expireTime);// 生效时间
        return JWTUtil.createToken(payload, JwtUtils.JWT_SECRET.getBytes());// 生成token
    }

    public static JWTPayload parseToken(String token){
        JWT jwt= JWTUtil.parseToken(token);
        boolean b=jwt.setKey(JWT_SECRET.getBytes()).verify();// 验证token的签名是否有效
        if(!b){
            throw new RuntimeException("token验证失败");
        }
        if (jwt.validate(0)){
            throw new RuntimeException("token已过期");
        }
        return jwt.getPayload();
    }

    public static void main(String[] args) {
        JWTPayload payload = JwtUtils.parseToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
                ".eyJuYmYiOjE3NTEwODg3NTEsIm5hbWUiOiLliJjog5wiLCJpZCI6MiwiZXhwIjoxNzUxMDg4NzUxLCJpYXQiOjE3NTEwODY5NTF9" +
                ".m2o5VBmEEPZwKxxzyWyPCW78cGOIfAtl4SLEp_mQcgw");
        String name = (String) payload.getClaim("name");
        System.out.println(name);
        System.out.println(payload.getClaim("id"));
        NumberWithFormat claim = (NumberWithFormat) payload.getClaim(JWTPayload.EXPIRES_AT);
        LocalDateTime convert = (LocalDateTime)claim.convert(LocalDateTime.class, claim);
        LocalDateTime now = LocalDateTime.now();
        long second = Duration.between(now, convert).getSeconds();
        System.out.println(second);
    }


}
